package br.com.foxline.atlasmobile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import br.com.foxline.atlasmobile.dao.EnderecoDao;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.entities.Endereco;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.entities.Proprietario;
import br.com.foxline.atlasmobile.enums.SituacaoImovel;

public class CorrespondenciaActivity extends Activity {

	private static String IMOVEL = "getimovel";

	String[] estados = new String[] { "PI", "AC", "AL", "AP", "AM", "BA", "CE",
			"DF", "ES", "GO", "MA", "MT", "MS", "MG", "PA", "PB", "PE", "RJ",
			"RN", "RS", "RO", "RR", "SC", "SP", "SE", "TO" };

	// DAO
	private ImovelDao imovelDao;

	private EnderecoDao enderecoDao;

	private Imovel imovel;

	private EditText logradouro;
	private EditText numero;
	private EditText comple;
	private EditText bairro;
	private EditText cep;
	private Spinner uf;

	private Endereco endereco;

	private EditText municipio;

	private CheckBox check;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_correspondencia);

		imovelDao = new ImovelDao(getApplicationContext());

		check = (CheckBox) findViewById(R.id.check_endereco_correspondencia);
		logradouro = (EditText) findViewById(R.id.logradouro_corre);
		numero = (EditText) findViewById(R.id.num_corre);
		cep = (EditText) findViewById(R.id.cep_corre);
		comple = (EditText) findViewById(R.id.compl_corre);
		bairro = (EditText) findViewById(R.id.nome_bairro_corre);
		municipio = (EditText) findViewById(R.id.municipio_corre);
		uf = (Spinner) findViewById(R.id.uf_corre);

		uf.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
				R.layout.spinner_item, estados));

		check.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean value) {
				if (value) {
					endereco = imovel.getEnderecoImovel();

					endereco.setId(null);

					logradouro.setText(endereco.getLogradouro());
					numero.setText(valueOf(endereco.getNumero()));
					comple.setText(endereco.getCompl());
					bairro.setText(endereco.getBairro());
					municipio.setText(endereco.getMunicipio() == null ? "Parnaíba"
							: (endereco.getMunicipio().equals("") ? "Parnaíba"
									: endereco.getMunicipio()));
					cep.setText(endereco.getCep());

					uf.setSelection(Arrays.asList(estados).indexOf(
							endereco.getUf()));

				} else {
					logradouro.setText("");
					numero.setText("");
					comple.setText("");
					bairro.setText("");
					municipio.setText("");
					cep.setText("");
					uf.setSelection(0);
				}
			}
		});

		if (getIntent().getSerializableExtra(IMOVEL) != null) {
			imovel = (Imovel) getIntent().getSerializableExtra(IMOVEL);

			imovel.getEnderecoCorrespondencia();

			enderecoDao = new EnderecoDao(getApplicationContext());

			if (imovel.getEnderecoCorrespondencia() != null) {
				endereco = imovel.getEnderecoCorrespondencia();

				logradouro.setText(endereco.getLogradouro());
				numero.setText(valueOf(endereco.getNumero()));
				comple.setText(endereco.getCompl());
				bairro.setText(endereco.getBairro());
				municipio.setText(endereco.getMunicipio());
				cep.setText(endereco.getCep());

				uf.setSelection(Arrays.asList(estados)
						.indexOf(endereco.getUf()));
			} else {
				endereco = new Endereco();
			}

		} else {
			imovel = new Imovel();
			endereco = new Endereco();
		}
	}

	public String valueOf(Integer x) {
		if (x != null) {
			return String.valueOf(x);
		}
		return "";
	}

	public void save() {
		enderecoDao = new EnderecoDao(getApplicationContext());
		imovelDao = new ImovelDao(getApplicationContext());

		endereco.setLogradouro(logradouro.getText().toString());
		endereco.setNumero(parseInt(numero.getText().toString()));
		endereco.setCompl(comple.getText().toString());
		endereco.setBairro(bairro.getText().toString());
		endereco.setCep(cep.getText().toString());
		endereco.setUf((String) uf.getSelectedItem());
		endereco.setMunicipio(municipio.getText().toString());

		if (endereco.getId() == null) {
			enderecoDao.create(endereco);
		} else {
			enderecoDao.update(endereco);
		}

		imovel.setEnderecoCorrespondencia(endereco);
		imovelDao.update(imovel);

	}

	public Integer parseInt(String str) {
		try {
			return (Integer.parseInt(str));
		} catch (Exception e) {
			return null;
		}

	}

	public void next(View view) {
		save();
		Intent intent = new Intent(getApplicationContext(),
				InfoGeralActivity.class);
		intent.putExtra(IMOVEL, imovel);
		startActivity(intent);
		// overridePendingTransition(R.anim.slide_in_right,
		// R.anim.slide_out_left);
		finish();
	}

	public void previous(View view) {
		save();
		Intent intent = new Intent(getApplicationContext(),
				DadosFamiliaresActivity.class);
		intent.putExtra("cont", true);
		intent.putExtra(IMOVEL, imovel);
		startActivity(intent);
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_correspondencia, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.finalizar:
			dialogSituacao();
			break;
		case R.id.sair:
			Intent intent = new Intent(this, MenuActivity.class);
			startActivity(intent);
			try {
				finalize();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void dialogSituacao() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Situação do Imóvel");

		final String[] items = new String[SituacaoImovel.values().length];
		int cont = 0;
		final Map<Integer, SituacaoImovel> map = new HashMap<Integer, SituacaoImovel>();

		for (SituacaoImovel si : SituacaoImovel.values()) {
			items[cont] = si.toString();
			map.put(cont, si);
			cont++;
		}

		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				imovel.setSituacaoImovel(map.get(which));
				save();
				imovel.getSituacaoImovel();
				finalCadastro();
			}
		});

		AlertDialog dsituacao = builder.create();
		dsituacao.show();
	}

	public void finalCadastro() {

		AlertDialog dialog;

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setNeutralButton("Finalizar e usar como modelo",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								CreateMainActivity.class);

						imovel.setId(null);

						if (imovel.getEnderecoImovel() != null)
							imovel.getEnderecoImovel().setId(null);
						if (imovel.getEnderecoCorrespondencia() != null)
							imovel.getEnderecoCorrespondencia().setId(null);
						if (imovel.getAnnex() != null) {
							imovel.setAnnex(null);
						}
						if (imovel.getDimensoes() != null) {
							imovel.getDimensoes().setId(null);
						}
						if (imovel.getProprietarios() != null) {
							for (Proprietario p : imovel.getProprietarios()) {
								p.setId(null);
							}
						}

						intent.putExtra(IMOVEL, imovel);

						startActivity(intent);
						finish();

					}
				});

		builder.setPositiveButton("Finalizar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								MenuActivity.class);
						startActivity(intent);
						finish();

					}
				});

		builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});

		builder.setMessage("Desejar finalizar o cadastro").setTitle(
				"Cadastro Finalizado");

		dialog = builder.create();
		dialog.show();
	}

}
